#include "font.h"
#include <allegro5/allegro_image.h>
#include <iostream>
#include <cstdlib>
using namespace std;

Font::Font(const string &imagefile, int width, int height) 
: m_width(width), m_height(height), m_pBitmap(NULL) {
     m_pBitmap = al_load_png(imagefile.c_str());
     if (!m_pBitmap) {
	  cout << "error loading font image" << endl;
	  exit(1);
     }
}

Font::~Font() {
     if (m_pBitmap) {
	  al_destroy_bitmap(m_pBitmap);
	  m_pBitmap = NULL;
     }
}

int Font::width() {
     return m_width;
}

int Font::height() {
     return m_height;
}

void Font::print(const string &str, Rect dest) {
     int c=0, off=0, x=0, w=0;
     int h = m_height;
     if (h > dest.height())
	  h = dest.height();
     for (size_t i=0; i<str.size(); i++) {
	  c = str[i];
	  x = dest.x() + i * m_width;
	  if (x > dest.x() + dest.width())
	       break;
	  w = m_width;
	  if (x + w > dest.x() + dest.width())
	       w = dest.x() + dest.width() - x;
	  off = c - '!'; // first printable char - first in image file
	  al_draw_bitmap_region(m_pBitmap, off*m_width,0,w,h,x,dest.y(), 0);
     }
}
